package controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import common.CommException;
import domain.User;
import Service.UserService;
/**
 * 登录请求处理控制器
 * @author cqyhm
 */
@WebServlet(urlPatterns="/login.do")
public class LoginServlet extends HttpServlet{

	private static final long serialVersionUID = -426931489150982181L;
	private Logger logger=LoggerFactory.getLogger(getClass());
	private UserService userService=new UserService();
	/**
	 * 处理get方法发送过来的请求
	 */
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
	/**
	 * 处理post方法发送过来的请求
	 */
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		logger.info("login.doPost");
		try {
			//1.接收前台传递过来的参数
			String usercode=req.getParameter("usercode");
			String password=req.getParameter("password");
			
			//2.参数类型转换
			//3.参数合法性校验
			if(usercode==null||usercode.length()<=0) {
				throw new CommException("账号不能为空");
			}
			if(password==null||password.length()<=0) {
				throw new CommException("密码不能为空");
			}
			
			HttpSession session=req.getSession();
		  
			//4.参数封装为对象
			//5.调用业务方法
			User user=userService.login(usercode, password);
			session.setAttribute("user", user);//把登录信息写到session中
			//6.转发或重定向(可传递数据给页面)
			resp.sendRedirect(req.getContextPath()+"/index.jsp");
			logger.info("登录成功");
		} catch (Exception e) {
			e.printStackTrace();
			req.setAttribute("error", e.getMessage());
			req.getRequestDispatcher("/login.jsp").forward(req, resp);
			logger.error("登录失败:{}",e.getMessage());
		}
	}
}
